module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('companies', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
      },
      tenant_id: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'tenants',
          key: 'id',
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
      },
      name: {
        type: Sequelize.STRING(255),
        allowNull: false,
        comment: '公司名称',
      },
      code: {
        type: Sequelize.STRING(50),
        allowNull: true,
        comment: '公司代码',
      },
      legal_name: {
        type: Sequelize.STRING(255),
        allowNull: true,
        comment: '法定名称',
      },
      tax_id: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: '税号/统一社会信用代码',
      },
      contact_person: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: '联系人',
      },
      contact_phone: {
        type: Sequelize.STRING(50),
        allowNull: true,
        comment: '联系电话',
      },
      contact_email: {
        type: Sequelize.STRING(255),
        allowNull: true,
        comment: '联系邮箱',
      },
      address: {
        type: Sequelize.TEXT,
        allowNull: true,
        comment: '地址',
      },
      description: {
        type: Sequelize.TEXT,
        allowNull: true,
        comment: '描述',
      },
      status: {
        type: Sequelize.ENUM('active', 'inactive', 'suspended'),
        allowNull: false,
        defaultValue: 'active',
        comment: '状态',
      },
      sort_order: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: '排序序号',
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      deleted_at: {
        type: Sequelize.DATE,
        allowNull: true,
      },
    });

    // 添加索引
    await queryInterface.addIndex('companies', ['tenant_id']);
    await queryInterface.addIndex('companies', ['status']);
    await queryInterface.addIndex('companies', ['code']);
    
    // 租户+公司代码唯一
    await queryInterface.addIndex('companies', ['tenant_id', 'code'], {
      unique: true,
      name: 'companies_tenant_id_code_unique',
      where: {
        code: { [Sequelize.Op.ne]: null },
        deleted_at: null,
      },
    });
  },

  down: async (queryInterface) => {
    await queryInterface.dropTable('companies');
  },
};

